package study.translation.interpreter;

import org.apache.log4j.Logger;
import study.translation.grammar.Grammar;
import study.translation.grammar.GrammarLoader;
import study.translation.grammar.ParseException;
import study.translation.parser.ComplexParser;
import study.translation.parser.ParseTree;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

public class Interpret
{
    private static final String GRAMMAR_FILE = "src/grammar/complex.grm";

    private static Logger log = Logger.getLogger( Interpret.class );

    public static void main( String[] args ) throws InterpretExcepton, IOException, ParseException
    {
        if( args.length < 1 )
        {
            log.info( "One argument (file name) required by the program." );
            return;
        }
        String filename = args[ 0 ];
        InputStream stream = null;
        try
        {
            GrammarLoader loader = new GrammarLoader( GRAMMAR_FILE );
            Grammar grammar = loader.load();

            stream = new FileInputStream( filename );
            ComplexParser parser = new ComplexParser( grammar );
            ParseTree tree = parser.parse( stream );


            StringWriter out = new StringWriter();
            SimpleInterpreter interpreter = new SimpleInterpreter( new PrintWriter( out ) );
            interpreter.interpret( tree );
            log.info( out );
        }
        catch( Exception e )
        {
            log.error( e.getMessage() );
        }
        finally
        {
            if( null != stream )
            {
                stream.close();
            }
        }
    }
}
